package ccm.itesm.mx.servicios;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ListaMenuLocales extends ListActivity {

	static String dir = "http://acampusandroid.appspot.com/getmenulocal?nombreServicio=";
	private ArrayList<Menu> platillos;
	String descr = "";
	String prec = "";
	String plat = "";
	
	//ProgressDialog progresa;
	
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.faltas);
		platillos = new ArrayList<Menu>();
		
		//Aqui obtengo el servicio seleccionado por el usuario
		Bundle b = this.getIntent().getExtras();
		int id = b.getInt("id");		
		
		cargaPlatillos(id);
		
		this.setListAdapter(new ArrayAdapter<Menu>(this, R.layout.listactivity, platillos));
	}
	
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		
		Menu men = (Menu) l.getItemAtPosition(position);
		
		descr = men.getDesc();
		prec = men.getPrecio();
		plat = men.getNombre();
				
		Dialog dialog = new Dialog(this);
		dialog.setContentView(R.layout.maindialog);
		dialog.setTitle(plat);
		
		TextView tvDesc = (TextView) dialog.findViewById(R.id.textViewDesc);
		//TextView tvPrec = (TextView) dialog.findViewById(R.id.textViewPrec);
		
		tvDesc.setText(descr + "\n\n" + prec);
		//tvPrec.setText(prec);
		
		dialog.show();
	}
	
	private void cargaPlatillos(int id){
				
		String consulta =  dir + id;
		String respuesta = download(consulta);
				
		if((respuesta != null) && !respuesta.startsWith("Error")){
			try {
				JSONArray platillosArr = new JSONArray(respuesta);
				
				if(platillosArr.length()>0){
					for (int i = 0; i < platillosArr.length(); i++) {
						JSONObject platilloConsultado = platillosArr.getJSONObject(i);
						this.platillos.add(new Menu(platilloConsultado.getString("name")
								, platilloConsultado.getString("desc")
								, platilloConsultado.getString("precio")));
					}
				}
				else{
					Toast.makeText(getBaseContext(), "No hay datos", Toast.LENGTH_LONG).show();
				}
			}
			catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private String download(String urlString){
        
		InputStream in = null;
        byte[] data = null;
        URLConnection conn = null;
        try{
        	URL url = new URL(urlString);
	    	conn = url.openConnection();
	        
	        if ((conn instanceof HttpURLConnection)){
	    		HttpURLConnection httpConn = (HttpURLConnection) conn;
	    		httpConn.setAllowUserInteraction(false);
	    		httpConn.setInstanceFollowRedirects(true);
	    		httpConn.setRequestMethod("GET");
	    		httpConn.connect();
	
	    		if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK){
	    			in = httpConn.getInputStream();
	    			ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    			int c;
	    			while((c = in.read()) > -1)
	                    baos.write(c);
	                data = baos.toByteArray();
	                baos.close();
	                in.close();
	                String str = new String(data);
	                System.out.println(str);
	                return str;
	    		}
	    		else{                
	    			return("Error reading data");
	            }
	        }
    	}
    	catch (Exception ex){
    		return "Error in connection";
    	}
    	finally{
            try{
                if (conn != null){
                    conn = null;
                }
                if (in != null){
                    in.close();
                    in = null;
                }

            }
            catch(IOException ex){
            	return("Error: "+ex.getMessage());
            }
        }   
    	return null;
    }
}
